package javase.ch05.tcp01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Desc 客户端
 * @Author chenmin
 * @Date 2025/11/3
 *
 * 需求3：服务端接收多条消息，服务端也可以发送多条消息；
 * 客户端可以发送多条消息，也可以接收多条消息；（一对一，阻塞的现象）
 *
 * 127.0.0.1  本机地址
 */
public class TCPClient {

    public static void main(String[] args) {
        System.out.println("---------- TCPClient ----------");
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader br = null;

        try {
            //第一个参数：IP地址   第二个参数：端口号
            socket = new Socket("192.168.0.152" , 8899);
            System.out.println("客户端正常启动！");

            Scanner sc = new Scanner(System.in);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());

            while (true){
                System.out.println("客户端说：");
                String str = sc.nextLine();

                //写消息
                out.println(str);
                out.flush();
                if(str.equals("exit")){
                    break;
                }

                //读消息
                String string = br.readLine();
                System.out.println("客户端接收到消息："+string);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(out!=null){
                out.close();
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
